package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.UserService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private  JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
     private StringRedisTemplate redisTemplate;
    @Override
    public PageResponse<UserVo> selectByPage(UserDto userDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        Page<UserVo> userVos = (Page<UserVo>)userMapper.findByPage(userDto);
        return PageResponse.of(userVos, UserVo.class);
    }

    @Override
    public UserVo login(LoginDto loginDto) {
//      1 判断用户是否存在 根据用户名
        User user=userMapper.longinByUsername(loginDto.getUsername());
        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }//如果不存在  则向前端抛出
            //判断是否被禁用
            if (user.getDataState().equals(SuperConstant.DATA_STATE_1)){
                throw  new BaseException(BasicEnum.COUNT_LOCK);   //自己定义的常量
            }
            //判断密码是否正确
            if (!BCrypt.checkpw(loginDto.getPassword(),user.getPassword())) {
                throw new BaseException(BasicEnum.PASSWORD_OR_USERNAME_ERROR);
            }
            //密码脱敏  不要在前端显示密码
            user.setPassword("");
            //使用工具生成jwt的字符串
            Map<String, Object> claims=new HashMap<>();
            UserVo userVo = BeanUtil.toBean(user, UserVo.class);
             claims.put("currentUser", JSONUtil.toJsonStr(userVo));
            String token=JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
            userVo.setUserToken(token);

            //获取白名单
            List<String> publicAccessUrls=securityConfigProperties.getPublicAccessUrls();
            //获取当前登录人的按钮资源 设计到sql语句
             List<String> urls=userMapper.findByUserId(user.getId());
             urls.addAll(publicAccessUrls);
             //添加到redis中
        redisTemplate.boundValueOps(CacheConstants.PUBLIC_ACCESS_URLS+user.getId()).set(JSONUtil.toJsonStr(urls),jwtTokenManagerProperties.getTtl(), TimeUnit.HOURS);
            return userVo;
        }

    }

